package com.rdc.example.service.impl;

import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.ArticleDTO;
import com.rdc.example.dao.impl.ArticleDaoImpl;
import com.rdc.example.dao.impl.CommentDaoImpl;
import com.rdc.example.dao.impl.LikeDaoImpl;
import com.rdc.example.dao.impl.UserDaoImpl;
import com.rdc.example.entity.Article;
import com.rdc.example.entity.User;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author duck
 */
public class ArticleServiceImpl implements com.rdc.example.service.ArticleService {

    ArticleDaoImpl articleDao = new ArticleDaoImpl();
    static ArticleServiceImpl articleService = new ArticleServiceImpl();
    Article articleEntity=new Article();
    List<Article> articleEntityList=new ArrayList<>();
    ArticleDTO articleDTO=new ArticleDTO();
    static List<ArticleDTO> articleDTOList=new ArrayList<>();

    public static void main(String[] args) {
        articleDTOList=articleService.listArticleSortByLikesDesc();
        System.out.println(articleDTOList);

    }



    /**
     * 通过userId找ta的文章在serival层操作多个dao
     * @param userId
     * @return List<ArticleDTO>
     */
    @Override
    public List<ArticleDTO> listArticleByUserId(Integer userId) {
        List<ArticleDTO> articleDTOList = new ArrayList<>();
        try {
            articleEntityList = articleDao.listArticleByUserId(userId);
            if (articleEntityList == null || articleEntityList.isEmpty()) {
                return articleDTOList;
            }
            UserDaoImpl userDao = new UserDaoImpl();
            User userEntity = userDao.getUserById(userId);
            if (userEntity == null) {
                System.err.println("用户不存在: userId=" + userId);
                return articleDTOList;
            }
            for (Article entity : articleEntityList) {
                ArticleDTO dto = convertToDto(entity);
                dto.setAuthor(userEntity.getUserName());
                articleDTOList.add(dto);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return articleDTOList;
    }

    /**
     * 创建文章
     * @param article
     * @return result
     */
    @Override
    public Result insertArticle(ArticleDTO article) {
        try{
            articleEntity=convertToEntity(article);
            boolean register=articleDao.insert(articleEntity);
            return register  ? Result.success("创建成功", null)
                    : Result.fail("创建失败", null);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新文章
     *
     * @param article
     * @return result
     */
    @Override
    public Result updateArticle(ArticleDTO article) {
        try{
            articleEntity=convertToEntity(article);
            boolean register=articleDao.update(articleEntity);
            return register  ? Result.success("修改成功", null)
                    : Result.fail("修改失败", null);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除文章
     *
     * @param articleId
     * @return result
     */
    @Override
    public Result deleteArticle(Integer articleId) {
        try{
            CommentDaoImpl commentDao = new CommentDaoImpl();
            LikeDaoImpl likeDao = new LikeDaoImpl();
            boolean registerArticle = articleDao.deleteById(articleId);
            boolean registerComment = commentDao.deleteByArticleId(articleId);
            boolean registerLike=  likeDao.deleteLikeByArticleId(articleId);

            return registerArticle&&registerComment&&registerLike  ? Result.success("删除成功", null)
                    : Result.fail("删除失败", null);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param articleId
     * @return
     */
    @Override
    public Result turnTopArticle(Integer articleId) {
        try{
            Article articleEntity=articleDao.getArticleById(articleId);
            boolean register=false;
            if(articleEntity.getIsTop()){
                register = articleDao.cancelTop(articleId);
            }else {
                register = articleDao.setTop(articleId);
            }
            return register  ? Result.success("修改成功", null)
                    : Result.fail("修改失败", null);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param articleId
     * @param columnId
     * @return
     */
    @Override
    public Result addColumn(Integer articleId, Integer columnId) {
        try{
            boolean register=articleDao.addColumn(articleId, columnId);
            return register  ? Result.success("修改成功", null)
                    : Result.fail("修改失败", null);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param articleId
     * @return
     */
    @Override
    public Result removeColumn(Integer articleId) {
        try{
            boolean register=articleDao.removeColumn(articleId);
            return register  ? Result.success("修改成功", null)
                    : Result.fail("修改失败", null);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 找所有文章
     * @return List<ArticleDTO>
     */
    @Override
    public List<ArticleDTO> listArticle() throws Exception {
        List<ArticleDTO> articleDTOList = new ArrayList<>();
        List<Article> articleEntityList = articleDao.listArticle();
        try {
            if (articleEntityList == null || articleEntityList.isEmpty()) {
                return articleDTOList;
                // 直接返回空列表
            }
            return convertAndEnrichArticles(articleEntityList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return articleDTOList;
    }
    /**
     * 按点赞数从高到低排序
     * @return
     */
    @Override
    public List<ArticleDTO> listArticleSortByLikesDesc() {
        List<ArticleDTO> articleDTOList = new ArrayList<>();
        try {
            // 1. 获取所有文章列表
            List<Article> articleEntityList = articleDao.listArticleSortByLikesDesc();
            if (articleEntityList == null || articleEntityList.isEmpty()) {
                return articleDTOList;
                // 直接返回空列表
            }
            return convertAndEnrichArticles(articleEntityList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return articleDTOList;
    }

    /**
     * 按评论时间从新到旧排序
     * @return
     */
    public List<ArticleDTO> listArticleSortByUpdatedAtDesc() {
        List<ArticleDTO> articleDTOList = new ArrayList<>();
        try {
            // 1. 获取所有文章列表
            List<Article> articleEntityList = articleDao.listArticleSortByUpdatedAtDesc();
            if (articleEntityList == null || articleEntityList.isEmpty()) {
                return articleDTOList;
                // 直接返回空列表
            }
            return convertAndEnrichArticles(articleEntityList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return articleDTOList;
    }

    /**
     *
     * @param columnId
     * @return
     */
    @Override
    public List<ArticleDTO> listArticleByColumnId(Integer columnId) {
        List<ArticleDTO> articleDTOList = new ArrayList<>();
        try {
            // 1. 获取所有文章列表
            List<Article> articleEntityList = articleDao.listArticleByColumnId(columnId);
            if (articleEntityList == null || articleEntityList.isEmpty()) {
                return articleDTOList;
                // 直接返回空列表
            }
            return convertAndEnrichArticles(articleEntityList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return articleDTOList;
    }

    /**
     *
     * @param articleIds
     * @return
     */
    @Override
    public List<ArticleDTO> listArticleByIds(List<Integer> articleIds) {
        List<ArticleDTO> articleDTOList = new ArrayList<>();
        try {
            List<Article> articleEntityList = articleDao.getArticleListByIds(articleIds);
            if (articleEntityList == null || articleEntityList.isEmpty()) {
                return articleDTOList;
            }
            return convertAndEnrichArticles(articleEntityList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return articleDTOList;
    }

    /**
     *
     * @param keyword
     * @return
     * @throws Exception
     */
    @Override
    public List<ArticleDTO> searchArticlesByName(String keyword) throws Exception {
        try {
            List<ArticleDTO> articleDTOList = new ArrayList<>();
            List<Article> articleList = articleDao.searchArticlesByTitle(keyword);
            if (articleList == null || articleList.isEmpty()) {
                return articleDTOList;
            }
            return convertAndEnrichArticles(articleList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private List<ArticleDTO> convertAndEnrichArticles(List<Article> articleEntityList) throws SQLException {
        List<ArticleDTO> dtos = new ArrayList<>();
        Set<Integer> userIds = articleEntityList.stream()
                .map(Article::getUserId)
                .collect(Collectors.toSet());
        UserDaoImpl userDao = new UserDaoImpl();
        Map<Integer, User> userMap = userDao.getUsersByIds(userIds);

        // 转换并填充作者信息
        for (Article entity : articleEntityList) {
            ArticleDTO dto = convertToDto(entity);
            User user = userMap.get(entity.getUserId());
            if (user != null) {
                dto.setAuthor(user.getUserName());
            } else {
                dto.setAuthor("未知");
                System.err.println("用户不存在: userId=" + entity.getUserId());
            }
            dtos.add(dto);
        }
        return dtos;
    }

    // 将entity.Article转换为bean.ArticleDTO
    private ArticleDTO convertToDto(Article entity) {
        ArticleDTO dto=new ArticleDTO();
        dto.setId(entity.getId());
        dto.setUserId(entity.getUserId());
        dto.setColumId(entity.getColumId());
        dto.setIsTop(entity.getIsTop());
        dto.setTitle(entity.getTitle());
        dto.setContent(entity.getContent());
        dto.setCreatedAt(entity.getCreatedAt());
        dto.setUpdatedAt(entity.getUpdatedAt());
        dto.setLikes(entity.getLikes());
        return dto;
    }

    // 将bean.ArticleDTO转换为entity.Article
    private Article convertToEntity(ArticleDTO dto) {
        Article entity=new Article();
        entity.setId(dto.getId());
        entity.setUserId(dto.getUserId());
        entity.setColumId(dto.getColumId());
        entity.setIsTop(dto.getIsTop());
        entity.setTitle(dto.getTitle());
        entity.setContent(dto.getContent());
        entity.setCreatedAt(dto.getCreatedAt());
        entity.setUpdatedAt(dto.getUpdatedAt());
        entity.setLikes(dto.getLikes());
        return entity;
    }
    // 将 List<Article>（entity）转换为 List<ArticleDTO>（bean）
    private List<ArticleDTO> convertToDtoList(List<Article> entities) {
        List<ArticleDTO> dtos = new ArrayList<>();
        for (Article entity : entities) {
            dtos.add(convertToDto(entity));
        }
        return dtos;
    }

    // 将 List<ArticleDTO>（bean）转换为 List<Article>（entity）
    private List<Article> convertToEntityList(List<ArticleDTO> dtos) {
        List<Article> entities = new ArrayList<>();
        for (ArticleDTO dto : dtos) {
            entities.add(convertToEntity(dto));
        }
        return entities;
    }

}
